﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Net;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;

using OpenCode.Modles;

namespace OpenCode
{
    /// <summary>
    /// 开奖方法
    /// </summary>
    public abstract class Lottery
    {
        /// <summary>
        /// 获取指定期的开奖号码
        /// </summary>
        /// <param name="issue">指定期号</param>
        public abstract Issue GetCurrentWin(string issue, DateTime opentime);

        /// <summary>
        /// 创建一个指定的用于开奖的彩种对像
        /// </summary>
        /// <param name="LotteryID">指定的彩种 ID</param>
        public static Lottery CreateLottery(int lotteryid)
        {
            return CreateLottery((LotteryType) lotteryid);
        }
        public static Lottery CreateLottery(LotteryType lotteryid)
        {
            Lottery rs = null;
            switch (lotteryid)
            {
                case LotteryType.SZPL:
                    rs = new SZPL();
                    break;
                case LotteryType.FC3D:
                    rs = new FS3D();
                    break;
                case LotteryType.CQSSC:
                    rs = new CQSSC();
                    break;
                case LotteryType.SHSSL:
                    rs = new SHSSL();
                    break;
                //case LotteryType.BJKL8:
                //    rs = new BJKL8();
                //break;
                case LotteryType.XJSSC:
                    rs = new XJSSC();
                    break;
                case LotteryType.HLJSSC:
                    rs = new HLJSSC();
                    break;
                case LotteryType.JXSSC:
                    rs = new JXSSC();
                    break;
                case LotteryType.TC11X5:
                    rs = new TC11X5();
                    break;
                case LotteryType.HaoCai1:
                    rs = new HaoCai1();
                    break;
                case LotteryType.GDKLSF:
                    rs = new GDKLSF();
                    break;
                default:
                    throw new System.ArgumentOutOfRangeException("LotteryID");
            }

            return rs;
        }
    }

    #region 实现类
    /// <summary>
    /// 排列3
    /// </summary>
    public class SZPL : Lottery
    {
        public override Issue GetCurrentWin(string issue, DateTime opentime)
        {
            // string url = "http://www.500wan.com/static/info/kaijiang/xml/plw/list10.xml";
            string url = "http://www.cailele.com/static/pw/newlyopenlist.xml";
            string qihao;
            string opencode;
            string strtime;
            //try
            //{
            //    XmlReaderSettings xs = new XmlReaderSettings();
            //    xs.XmlResolver = null;
            //    xs.ProhibitDtd = false;
            //    XmlReader reader = XmlReader.Create(url, xs);
            //    XmlDocument doc = new XmlDocument();
            //    doc.Load(reader);
            //    var row = doc.ChildNodes[1]["row"];
            //    qihao = row.Attributes["expect"].Value;
            //    opencode = row.Attributes["opencode"].Value;
            //    strtime = row.Attributes["opentime"].Value;
            //}
            //catch
            //{

            //}
            try
            {
                DataSet objDataSet = new DataSet();
                objDataSet.ReadXml(url);
                //取得期号
                qihao = objDataSet.Tables[0].Rows[0]["expect"] as string;
                //取得开奖号码
                opencode = objDataSet.Tables[0].Rows[0]["opencode"] as string;

                strtime = objDataSet.Tables[0].Rows[0]["opentime"] as string;
                objDataSet.Dispose();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message + "(注:GetCurrentWin)");
            }
            DateTime getopen;

            if (string.IsNullOrEmpty(strtime) || !DateTime.TryParse(strtime.Trim(), out getopen) || string.IsNullOrEmpty(opencode))
                throw new System.NullReferenceException(LotteryType.SZPL + "开奖：文件解析出错！");

            opencode = opencode.Replace(",", "");
            opencode = opencode.Substring(0, 3);

            Issue open = new Issue() { Number = issue, WinNumber = opencode, LotteryID = (int)LotteryType.SZPL };
            string openissue = issue.Substring(2, 5);
            if (getopen > opentime)
                open.IsNull = true;
            if (!openissue.Equals(qihao))
            {
                return null;
            }
            //else if (getopen < opentime)
            //    return null;
            //DateTime todaytime=DateTime.Parse(DateTime.Now.ToShortDateString());
            //if (opentime < todaytime)
            //{
            //    return null;

            //}

            return open;
        }
    }

    /// <summary>
    /// 福彩3D
    /// </summary>
    public class FS3D : Lottery
    {

        public override Issue GetCurrentWin(string issue, DateTime opentime)
        {
            DataSet objDataSet = new DataSet();

            //备用    string url = "http://www.cailele.com/static/3d/newlyopenlist.xml";
            objDataSet.ReadXml("http://www.500wan.com/static/info/kaijiang/xml/sd/list10.xml");
            //取得期号
            string qihao = objDataSet.Tables[0].Rows[0]["expect"] as string;
            //取得开奖号码
            string opencode = objDataSet.Tables[0].Rows[0]["opencode"] as string;

            string strtime = objDataSet.Tables[0].Rows[0]["opentime"] as string;

            objDataSet.Dispose();
            DateTime getopen;

            if (string.IsNullOrEmpty(strtime) || !DateTime.TryParse(strtime.Trim(), out getopen) || string.IsNullOrEmpty(opencode))
                throw new System.NullReferenceException(LotteryType.FC3D + "开奖：文件解析出错！");

            opencode = opencode.Replace(",", "");

            Issue open = new Issue() { Number = issue, WinNumber = opencode, LotteryID = (int)LotteryType.FC3D };

            if (getopen > opentime)
                open.IsNull = true;

            else if (getopen < opentime)
                return null;

            return open;
        }
    }

    /// <summary>
    /// 重庆时时彩
    /// </summary>
    public class CQSSC : Lottery
    {

        //*  private static string url1 = "http://www.178cpw.com//public/kj_getxml.php?cptype=ssc";*//
        private static string url2 = "http://www.500wan.com/static/public/ssc/xml/newlyopen.xml";
        private static string url3 = "http://www.cailele.com/static/ssc/newlyopenlist.xml";//备用
        public override Issue GetCurrentWin(string issue, DateTime opentime)
        {
            Issue rs = null;
            rs = GetCurrentWin2(issue, opentime);
            if (rs == null)
                rs = GetCurrentWin1(issue, opentime);
            //if (rs == null)
            //    rs = GetCurrentWin0(issue, opentime);
            return rs;
        }

        #region 老的开奖地址
        /// <summary>
        /// 时时彩
        /// </summary>
        public Issue GetCurrentWin0(string issue, DateTime opentime)
        {
            Issue rs = null;

            string url = "http://video.shishicai.cn/BetAjax.aspx";
            string refurl = "http://www.shishicai.cn/Lottery/Speed/FCCQSSC/Base.aspx";
            var data1 = new System.Text.ASCIIEncoding().GetBytes("data=4|3");
            url += string.Format("?method=&randomStr={0}", Math.Round(197544d));
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
            request.Method = WebRequestMethods.Http.Post;
            request.Headers.Add("Origin", "http://video.shishicai.cn");
            request.Referer = refurl; ;
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.9 (KHTML, like Gecko) Chrome/7.0.530.0 Safari/534.9";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = new CookieContainer();
            var sm = request.GetRequestStream();
            sm.Write(data1, 0, data1.Length);
            sm.Close();

            WebResponse response = request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();
            response.Close();
            var tmp = content.Split("()';".ToCharArray());
            if (tmp.Length != 13)
                throw new Exception("请求的结果格式不一致，无法解析！");

            string qihao = tmp[6];
            string opencode = tmp[7];
            if (string.IsNullOrEmpty(qihao) || string.IsNullOrEmpty(opencode))
                return null;
            long intqihao = long.Parse(qihao.Replace("-", ""));
            long intissue = long.Parse(issue.Replace("-", ""));

            if (intqihao < intissue)
                return null;
            rs = new Issue() { Number = qihao, WinNumber = opencode, LotteryID = (int)LotteryType.CQSSC, IsNull = intqihao > intissue };

            return rs;
        }
        /// <summary>
        /// 500万
        /// </summary>
        public Issue GetCurrentWin1(string issue, DateTime opentime)
        {
            Issue rs = null;
            string keyNameQihao = "";
            string keyNameOpencode = "";
            bool is500Wan = false;

            string qihao = "";
            long intqihao = 0;
            var str = issue.Replace("-", "");
            str = str.Substring(str.Length - 9);
            long intissue = long.Parse(str);
            string opencode = "";

            DataSet objDataSet = new DataSet();

            try
            {
                objDataSet.ReadXml(url2);
                keyNameQihao = "qishu";
                keyNameOpencode = "code";
            }
            catch { }

            if (objDataSet == null || objDataSet.Tables.Count == 0 || objDataSet.Tables[0].Rows.Count == 0 || !(objDataSet.Tables[0].Columns.Contains(keyNameQihao) && objDataSet.Tables[0].Columns.Contains(keyNameOpencode)))
            {
                try
                {
                    objDataSet.Tables.Clear();
                    objDataSet.ReadXml(url2);
                    is500Wan = true;
                }
                catch
                {
                    return null;
                }
                keyNameQihao = "expect";
                keyNameOpencode = "opencode";
                is500Wan = true;
            }

            if (objDataSet == null || objDataSet.Tables.Count == 0 || objDataSet.Tables[0].Rows.Count == 0)
                return null;

            qihao = objDataSet.Tables[0].Rows[0][keyNameQihao] as string;
            opencode = objDataSet.Tables[0].Rows[0][keyNameOpencode] as string;
            if (!string.IsNullOrEmpty(qihao) && !string.IsNullOrEmpty(opencode))
            {
                qihao = qihao.Trim();
                str = qihao.Replace("-", "");
                str = str.Substring(str.Length - 9);
                intqihao = long.Parse(str);
                qihao = qihao.Insert(8, "-");
            }

            if (intqihao < intissue)
            {
                if (is500Wan)
                    return null;

                try
                {
                    objDataSet.Tables.Clear();
                    objDataSet.ReadXml(url2);
                    is500Wan = true;
                }
                catch
                {
                    return null;
                }
                keyNameQihao = "expect";
                keyNameOpencode = "opencode";
                is500Wan = true;

                qihao = objDataSet.Tables[0].Rows[0][keyNameQihao] as string;
                opencode = objDataSet.Tables[0].Rows[0][keyNameOpencode] as string;

                if (!string.IsNullOrEmpty(qihao) && !string.IsNullOrEmpty(opencode))
                {
                    qihao = qihao.Trim();
                    str = qihao.Replace("-", "");
                    str = str.Substring(str.Length - 9);
                    intqihao = long.Parse(str);
                    qihao = qihao.Insert(8, "-");
                }

                if (intqihao < intissue)
                    return null;
            }
            objDataSet.Dispose();

            if (is500Wan)
                opencode = opencode.Replace(",", "");
            if (intqihao < intissue)
                return null;
            rs = new Issue() { Number = qihao, WinNumber = opencode, LotteryID = (int)LotteryType.CQSSC, IsNull = intqihao > intissue };

            return rs;
        }
        /// <summary>
        /// 彩彩乐
        /// </summary>
        public Issue GetCurrentWin2(string issue, DateTime opentime)
        {
            Issue rs = null;
            DataSet objDataSet = new DataSet();

            objDataSet.ReadXml("http://www.cailele.com/static/ssc/newlyopenlist.xml");
            //取得期号
            string qihao = objDataSet.Tables[0].Rows[0]["expect"] as string;
            //取得开奖号码
            string opencode = objDataSet.Tables[0].Rows[0]["opencode"] as string;

            objDataSet.Dispose();
            opencode = opencode.Replace(",", "");
            var intqihao = long.Parse(qihao);
            var intissue = long.Parse(issue.Replace("-", ""));
            if (intqihao < intissue)
                return null;
            rs = new Issue() { Number = qihao, WinNumber = opencode, LotteryID = (int)LotteryType.CQSSC, IsNull = intqihao > intissue };

            return rs;
        }
        #endregion
    }




    /// <summary>
    /// 上海时时乐
    /// </summary>
    public class SHSSL : Lottery
    {
        //private static string url1 = "http://www.178cpw.com//public/kj_getxml.php?cptype=ssl";
        //    private static string url1 = "http://kjh.cailele.com/history_shssl.aspx";
        // private static string url2 = "http://trade.500wan.com/static/public/ssl/xml/opencode.xml";
        private static string url1 = "http://www.cailele.com/static/ssl/newlyopenlist.xml";
        public override Issue GetCurrentWin(string issue, DateTime opentime)
        {
            //    Issue rs = null;
            //    string keyNameQihao = "";
            //    string keyNameOpencode = "";
            //    bool is500Wan = false;

            //    string qihao = "";
            //    string opencode = "";
            //    long intqihao = 0;
            //    long intissue = long.Parse(issue.Replace("-", ""));

            //    DataSet objDataSet = new DataSet();

            //    try
            //    {
            //        objDataSet.ReadXml(url1);
            //        keyNameQihao = "qishu";
            //        keyNameOpencode = "code";
            //    }
            //    catch
            //    {

            //    }
            //    if (objDataSet == null || objDataSet.Tables.Count == 0 || objDataSet.Tables[0].Rows.Count == 0 || !(objDataSet.Tables[0].Columns.Contains(keyNameQihao) && objDataSet.Tables[0].Columns.Contains(keyNameOpencode)))
            //    {
            //        try
            //        {
            //            objDataSet.Tables.Clear();
            //            objDataSet.ReadXml(url1);
            //            is500Wan = true;
            //        }
            //        catch
            //        {
            //            return null;
            //        }
            //        keyNameQihao = "expect";
            //        keyNameOpencode = "opencode";
            //        is500Wan = true;
            //    }


            //    if (objDataSet == null || objDataSet.Tables.Count == 0 || objDataSet.Tables[0].Rows.Count == 0)
            //        return null;

            //    qihao = objDataSet.Tables[0].Rows[0][keyNameQihao] as string;
            //    opencode = (objDataSet.Tables[0].Rows[0][keyNameOpencode] as string);

            //    if (!string.IsNullOrEmpty(qihao) && !string.IsNullOrEmpty(opencode))
            //    {
            //        qihao = qihao.Trim();
            //        intqihao = long.Parse(qihao.Replace("-", ""));
            //        if (!is500Wan)
            //            qihao = qihao.Insert(8, "-");
            //    }
            //    if (intqihao < intissue)
            //    {
            //        if (is500Wan)
            //            return null;

            //        try
            //        {
            //            objDataSet.Tables.Clear();
            //            objDataSet.ReadXml(url1);
            //            is500Wan = true;
            //        }
            //        catch
            //        {
            //            return null;
            //        }
            //        keyNameQihao = "expect";
            //        keyNameOpencode = "opencode";
            //        is500Wan = true;

            //        qihao = objDataSet.Tables[0].Rows[0][keyNameQihao] as string;
            //        opencode = objDataSet.Tables[0].Rows[0][keyNameOpencode] as string;

            //        if (string.IsNullOrEmpty(qihao) || string.IsNullOrEmpty(opencode))
            //            return null;

            //        qihao = qihao.Trim();
            //        intqihao = long.Parse(qihao.Replace("-", ""));

            //    }

            //    objDataSet.Dispose();

            //    if (is500Wan)
            //        opencode = opencode.Replace(",", "");
            //    if (intqihao < intissue)
            //        return null;
            //    rs = new Issue() { Number = qihao, WinNumber = opencode, LotteryID = (int)LotteryType.SHSSL, IsNull = intqihao > intissue };

            //    return rs;
            string url = "http://baidu.lehecai.com/lottery/draw/view/201?phase=&agentId=5555";
            string opencode = "";
            string qihao = "";


            var client = new WebClient();

            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");


            var data = client.OpenRead(url);

            var reader = new StreamReader(data, Encoding.Default);

            string html = reader.ReadToEnd();
            opencode = html.Substring(html.IndexOf("latest_draw_result =") + 30, 10);
            opencode = opencode.Replace("\"", "");
            opencode = opencode.Replace(",", "");
            qihao = html.Substring(html.IndexOf("latest_draw_phase =") + 21, 10);
            var intqihao = long.Parse(qihao);
            var intissue = long.Parse(issue.Replace("-", ""));
            var rs = new Issue() { Number = qihao, WinNumber = opencode, LotteryID = (int)LotteryType.SHSSL, IsNull = intqihao > intissue };
            if (intqihao < intissue)
                return null;

            return rs;
        }
    }

    ///// <summary>
    ///// 北京快乐8
    ///// </summary>
    //public class BJKL8 : Lottery
    //{
    //    public override Issue GetCurrentWin(string issue, DateTime opentime)
    //    {
    //        Issue rs = null;

    //        WebRequest request = WebRequest.Create("http://www.bjfcdt.gov.cn/DataCenter/GetTVPlusInfo.aspx");

    //        request.UseDefaultCredentials = false;
    //        WebResponse response = request.GetResponse();
    //        Stream resStream = response.GetResponseStream();
    //        StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
    //        string txtUrlContent = sr.ReadToEnd();
    //        resStream.Close();
    //        sr.Close();

    //        string[] ssContent = txtUrlContent.Split('&');
    //        string qihao = ssContent[1].Remove(0, 14); //本期期号
    //        string opencode = ssContent[4].Remove(0, 9).Replace("|", " ");　//开奖号码

    //    //    string hljissue = System.Configuration.ConfigurationManager.AppSettings["hljissue"];
    //    //string wintime = System.Configuration.ConfigurationManager.AppSettings["wintime"];
    //    //string strDate = strValue.Substring(0, 8);
    //    //string strOldQh = strValue.Substring(9, 2);
    //    //string strGetDate = strDate.Substring(0, 4) + "-" + strDate.Substring(4, 2) + "-" + strDate.Substring(6, 2) + " 10:10:01";
    //    //TimeSpan dtDays = Convert.ToDateTime(strGetDate) - Convert.ToDateTime(wintime);
    //    //int numNewQh = dtDays.Days * 84 + Convert.ToInt32(strOldQh) + Convert.ToInt32(hljissue) - 1;
    //    //int numLength = numNewQh.ToString().Trim().Length;
    //    //string strNewQh = numNewQh.ToString();
    //    //for (int i = 0; i < 7 - numLength; i++)
    //    //{
    //    //    strNewQh = "0" + strNewQh;
    //    //}

    //        //判断开奖号码是否开完整
    //        //if (issue.Equals(qihao)&&opencode.Length == 59)
    //            rs = new Issue() { Number=qihao, WinNumber=opencode,LotteryID=(int)LotteryType.BJKL8,IsNull=true };

    //        return rs;
    //    }
    //}

    /// <summary>
    /// 新疆时时彩
    /// </summary>
    public class XJSSC : Lottery
    {
        private static string url = "http://www.xjflcp.com/servlet/sscSaleEnd?flag=openPrize";

        public override Issue GetCurrentWin(string issue, DateTime opentime)
        {
            Issue rs = null;

            DataSet objDataSet = new DataSet();

            //时时彩
            objDataSet.ReadXml(url);
            //取得期号
            string qihao = objDataSet.Tables[0].Rows[0]["lottery_draw"] as string;
            //取得开奖号码
            string opencode = objDataSet.Tables[0].Rows[0]["open_result"] as string;
            objDataSet.Dispose();
            if (string.IsNullOrEmpty(qihao) || string.IsNullOrEmpty(opencode))
                return null;

            qihao = qihao.Trim();
            long intqihao = long.Parse(qihao);
            long intissue = long.Parse(issue.Replace("-", ""));
            qihao.Insert(8, "-");
            opencode = opencode.Replace(" ", "");
            if (intqihao < intissue)
                return null;
            rs = new Issue() { Number = qihao, WinNumber = opencode, LotteryID = (int)LotteryType.XJSSC, IsNull = intqihao > intissue };

            return rs;
        }
    }

    /// <summary>
    /// 黑龙江时时彩
    /// </summary>
    public class HLJSSC : Lottery
    {
        public override Issue GetCurrentWin(string issue, DateTime opentime)
        {
            return GetCurrentWin_shishicai(issue, opentime);
        }
        private Issue GetCurrentWin0(string issue, DateTime opentime)
        {
            Issue rs = null;
            string url = "http://caipiao.vodone.com/luckynumber/newsscnumbernew.xml";
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(url);
            XmlNode xnQihao = xmlDoc.SelectSingleNode("/root/open_expect");
            XmlNode xnWan = xmlDoc.SelectSingleNode("/root/open_number/wan_num");
            XmlNode xnQian = xmlDoc.SelectSingleNode("/root/open_number/qian_num");
            XmlNode xnBai = xmlDoc.SelectSingleNode("/root/open_number/bai_num");
            XmlNode xnShi = xmlDoc.SelectSingleNode("/root/open_number/shi_num");
            XmlNode xnGe = xmlDoc.SelectSingleNode("/root/open_number/ge_num");


            string opencode = xnWan.InnerText + xnQian.InnerText + xnBai.InnerText + xnShi.InnerText + xnGe.InnerText;
            string qihao = xnQihao.InnerText;

            //计算期号            
            //string hljissue = System.Configuration.ConfigurationManager.AppSettings["HLJSSC_ReferenceIssue"];
            //string wintime = System.Configuration.ConfigurationManager.AppSettings["HLJSSC_ReferenceTime"];
            //int numNewQH = Convert.ToInt32(qihao);
            //int numOldQH = Convert.ToInt32(hljissue);
            //int numSpanQH = numNewQH - numOldQH;
            //int numDaySpan = numSpanQH / 84;         //间隔天数
            //int numDayQhs = numSpanQH - numDaySpan * 84;  //当天间隔期数
            //string strDayQhs = "";
            //if (numDayQhs < 9)
            //{
            //    strDayQhs = "0" + (numDayQhs + 1).ToString();
            //}
            //else
            //{
            //    strDayQhs = (numDayQhs + 1).ToString();
            //}

            //DateTime dtNewTime = Convert.ToDateTime(wintime).AddDays(numDaySpan);
            //qihao = dtNewTime.ToString("yyyyMMdd") + "-" + strDayQhs;

            if (string.IsNullOrEmpty(qihao) || string.IsNullOrEmpty(opencode))
                return null;

            long intqihao = long.Parse(qihao);
            long intissue = long.Parse(issue);

            if (intqihao < intissue)
                return null;

            rs = new Issue() { Number = issue, WinNumber = opencode, LotteryID = (int)LotteryType.HLJSSC, IsNull = intqihao > intissue };

            return rs;
        }
        private Issue GetCurrentWin_shishicai(string issue, DateTime opentime)
        {
            Issue rs = null;

            string url = "http://video.shishicai.cn/haoma/hljssc/list/84.aspx";
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
            request.Method = WebRequestMethods.Http.Get;
            request.Referer = "http://www.shishicai.cn/ssc/hljssc/bet.aspx"; ;
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7";
            request.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
            request.CookieContainer = new CookieContainer();

            WebResponse response = request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();
            response.Close();

            var tmp = GetIssueAndOpenCode(content);
            if (string.IsNullOrEmpty(tmp.Key) || string.IsNullOrEmpty(tmp.Value))
                throw new Exception("请求的结果格式不一致，无法解析！");

            string qihao = tmp.Key;
            string opencode = tmp.Value;
            if (string.IsNullOrEmpty(qihao) || string.IsNullOrEmpty(opencode))
                return null;
            long intqihao = long.Parse(qihao.Replace("-", ""));
            long intissue = long.Parse(issue.Replace("-", ""));

            if (intqihao < intissue)
                return null;
            rs = new Issue() { Number = qihao, WinNumber = opencode, LotteryID = (int)LotteryType.CQSSC, IsNull = intqihao > intissue };

            return rs;

        }
        /// <summary>
        /// 根据网页内容获取开奖号码和期号，返回结果的键为期号值为开奖号码
        /// </summary>
        /// <param name="responseContent"></param>
        /// <returns></returns>
        private KeyValuePair<string, string> GetIssueAndOpenCode(string responseContent)
        {
            try
            {
                Regex r = new Regex(@"var\s+listIssue\s+=\s+\[{(.\n?)+\d""}\];?");
                var math = r.Match(responseContent);
                if (math == null || string.IsNullOrEmpty(math.Value))
                    return new KeyValuePair<string, string>("", "");
                var str = math.Value;
                var index = str.IndexOf('{');
                str = str.Substring(index + 1, str.IndexOf('}') - index - 1 - 1);
                var list = str.Split(new string[] { "\",\"" }, StringSplitOptions.RemoveEmptyEntries);
                var result = new KeyValuePair<string, string>(
                    list.FirstOrDefault(p => p.Replace("\"", "").StartsWith("IssueNumber")).Replace("\"", "").Split(':')[1].Substring(1),
                    list.FirstOrDefault(p => p.Replace("\"", "").StartsWith("BonusNumberString")).Replace("\"", "").Split(':')[1].Split('|')[0].Replace(",", ""));
                return result;
            }
            catch
            {
                return new KeyValuePair<string, string>("", "");
            }
        }
    }

    /// <summary>
    /// 江西时时彩
    /// </summary>
    public class JXSSC : Lottery
    {
        private static CookieCollection _Cookies;
        public override Issue GetCurrentWin(string issue, DateTime opentime)
        {
            Issue rs = null;
            rs = GetCurrentWin3(issue, opentime);
            return rs;
        }

        public Issue GetCurrentWin0(string issue, DateTime opentime)
        {
            Issue rs = null;

            string url = "http://video.shishicai.cn/BetAjax.aspx";
            string refurl = "http://www.shishicai.cn/Lottery/Speed/FCJXSSC/Base.aspx";
            string d = "data=5|3";
            var data1 = new System.Text.ASCIIEncoding().GetBytes(d);
            url += string.Format("?method=&randomStr={0}", Math.Round(197544d));
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
            request.Method = WebRequestMethods.Http.Post;
            request.Headers.Add("Host", "video.shishicai.cn");
            request.Headers.Add("Origin", "http://video.shishicai.cn");
            request.Referer = refurl; ;
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.11 (KHTML, like Gecko) Chrome/9.0.565.0 Safari/534.11";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = new CookieContainer();
            if (_Cookies != null)
                request.CookieContainer.Add(_Cookies);
            var sm = request.GetRequestStream();
            sm.Write(data1, 0, data1.Length);
            sm.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();
            if (response.Cookies.Count > 0)
            {
                _Cookies = new CookieCollection();
                _Cookies.Add(response.Cookies);
            }
            response.Close();
            var tmp = content.Split("(),';".ToCharArray());
            if (tmp.Length != 14)
                throw new Exception("请求的结果格式不一致，无法解析！");

            string qihao = tmp[6];
            string opencode = tmp[7];
            if (string.IsNullOrEmpty(qihao) || string.IsNullOrEmpty(opencode))
                return null;
            long intqihao = long.Parse(qihao.Replace("-0", ""));
            long intissue = long.Parse(issue.Replace("-", ""));

            if (intqihao < intissue)
                return null;
            rs = new Issue() { Number = qihao, WinNumber = opencode, LotteryID = (int)LotteryType.JXSSC, IsNull = intqihao > intissue };

            return rs;
        }

        public Issue GetCurrentWin1(string issue, DateTime opentime)
        {
            Issue rs = null;
            DataSet objDataSet = new DataSet();

            objDataSet.ReadXml("http://trade.cpdyj.com/staticdata/lotteryinfo/jxssc/xml/opencode.xml");
            //取得期号
            string qihao = objDataSet.Tables[0].Rows[0]["expect"] as string;
            //取得开奖号码
            string opencode = objDataSet.Tables[0].Rows[0]["opencode"] as string;

            objDataSet.Dispose();

            var intqihao = long.Parse(qihao);
            var intissue = long.Parse(issue.Replace("-", "0").Substring(2));
            if (intqihao < intissue)
                return null;
            rs = new Issue() { Number = qihao, WinNumber = opencode, LotteryID = (int)LotteryType.CQSSC, IsNull = intqihao > intissue };

            return rs;
        }

        public Issue GetCurrentWin2(string issue, DateTime opentime)
        {
            //string url = "http://kjh.cailele.com/history_jxssc.aspx";
            //string opencode = "";
            //string qihao = "";


            //var client = new WebClient();

            //client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");


            //var data = client.OpenRead(url);

            //var reader = new StreamReader(data, Encoding.Default);

            //string html = reader.ReadToEnd();
            //html = html.Substring(html.IndexOf("历史开奖公告", 1000));
            //html = html.Replace("\r\n", "");

            //Regex reg = new Regex(@"[\d]{9}");
            //Regex num = new Regex(@">([\d])<");
            //Match match = reg.Match(html);
            //qihao = match.Value;
            //match = num.Match(html, match.Index);
            //for (int i = 0; i < 5; i++)
            //{
            //    opencode += match.Value;
            //    match = match.NextMatch();
            //}
            //opencode = opencode.Replace("<", "").Replace(">", "");
            WebClient wc = new WebClient();
            wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            StreamReader sr = new StreamReader(wc.OpenRead("http://kjh.cailele.com/history_jxssc.aspx"), Encoding.Default);
            string html = sr.ReadToEnd();

            Regex rg = new Regex("<div[^<>]+?class=[\"']ball_yellow[\"'][^<>]?>(?<num>\\d{1,})</div>", RegexOptions.IgnoreCase);

            MatchCollection mts = rg.Matches(html);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mts.Count; i++)
            {
                sb.Append(mts[i].Groups["num"].Value);
                if (i == 4)
                    break;
            }
            string opencode = sb.ToString();

            rg = new Regex("<td[^<>]*?>(?<num>\\d{9})</td>");
            Match mt = rg.Match(html);
            string qihao = mt.Groups["num"].Value;

            var intqihao = long.Parse(qihao);
            var intissue = long.Parse(issue.Replace("-", "0").Substring(2));
            if (intqihao < intissue)
                return null;

            rg = new Regex("<td[^<>]+?align=[\"']center[\"'][^<>]?>(?<num>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2})</td>");
            mt = rg.Match(html);
            string time = mt.Groups["num"].Value;
            var rs = new Issue() { Number = qihao, WinNumber = opencode, LotteryID = (int)LotteryType.JXSSC, IsNull = intqihao > intissue };

            return rs;
        }

        public Issue GetCurrentWin3(string issue, DateTime opentime)
        {
            Issue rs = null;

            string url = string.Format("http://data.shishicai.cn/jxssc/haoma/?t={0}", DateTime.Now.Ticks);
            string refurl = "http://www.shishicai.cn/";

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
            request.Method = WebRequestMethods.Http.Get;
            request.Headers.Add("Origin", "http://video.shishicai.cn");
            request.Referer = refurl; ;
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.11 (KHTML, like Gecko) Chrome/9.0.565.0 Safari/534.11";
            request.CookieContainer = new CookieContainer();
            if (_Cookies != null)
                request.CookieContainer.Add(_Cookies);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();
            if (response.Cookies.Count > 0)
            {
                _Cookies = new CookieCollection();
                _Cookies.Add(response.Cookies);
            }
            response.Close();

            var match = Regex.Match(content, @"江西时时彩第(?<Issue>[-0-9]{12})期开奖号码:(?<Number>\d{5}),开奖时间:(?<Date>[-: 0-9]{16})");
            if(!match.Success)
                throw new Exception("请求的结果格式不一致，无法解析！");

            string qihao = match.Groups["Issue"].Value;
            string opencode = match.Groups["Number"].Value;
            if (string.IsNullOrEmpty(qihao) || string.IsNullOrEmpty(opencode))
                return null;
            long intqihao = long.Parse(qihao.Replace("-0", ""));
            long intissue = long.Parse(issue.Replace("-", ""));

            if (intqihao < intissue)
                return null;
            rs = new Issue() { Number = qihao, WinNumber = opencode, LotteryID = (int)LotteryType.JXSSC, IsNull = intqihao > intissue };

            return rs;
        }
    }

    /// <summary>
    /// 11选5
    /// </summary>
    public class TC11X5 : Lottery
    {
        //*http://www.cailele.com/static/gd11x5/newlyopenlist.xml *//
        private static string url1 = "http://www.cailele.com/interface/GetCurrentTerm?type=getOpen&lotteryType=52";//备用
        public override Issue GetCurrentWin(string issue, DateTime opentime)
        {
            Issue rs = null;

            rs = GetCurrentWin2(issue, opentime);
            //if (rs == null)
            //    rs = GetCurrentWin1(issue, opentime);
            return rs;
        }
        /// <summary>
        /// 时时彩
        /// </summary>
        public Issue GetCurrentWin1(string issue, DateTime opentime)
        {
            Issue rs = null;
            string url = "http://video.shishicai.cn/BetAjax.aspx";
            string refurl = "http://www.shishicai.cn/Lottery/Speed/TCDLC/Base.aspx";
            var data1 = new System.Text.ASCIIEncoding().GetBytes("data=23|3");
            url += string.Format("?method=&randomStr={0}", Math.Round(197544d));
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
            request.Method = WebRequestMethods.Http.Post;
            request.Headers.Add("Origin", "http://video.shishicai.cn");
            request.Referer = refurl; ;
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.8 (KHTML, like Gecko) Chrome/7.0.524.0 Safari/534.8";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = new CookieContainer();
            var sm = request.GetRequestStream();
            sm.Write(data1, 0, data1.Length);
            sm.Close();

            WebResponse response = request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();
            response.Close();
            var tmp = content.Split("()';".ToCharArray());
            if (tmp.Length != 13)
                throw new Exception("请求的结果格式不一致，无法解析！");

            string qihao = tmp[6];
            string opencode = tmp[7];
            if (string.IsNullOrEmpty(qihao) || string.IsNullOrEmpty(opencode))
                return null;
            long intqihao = long.Parse(qihao.Replace("-", ""));
            long intissue = long.Parse(issue.Replace("-", ""));

            if (intqihao < intissue)
                return null;
            rs = new Issue() { Number = qihao, WinNumber = opencode, LotteryID = (int)LotteryType.TC11X5, IsNull = intqihao > intissue };

            return rs;
        }
        /// <summary>
        /// 彩彩乐
        /// </summary>
        public Issue GetCurrentWin2(string issue, DateTime opentime)
        {
            Issue rs = null;

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url1);
            request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
            request.Method = WebRequestMethods.Http.Get;
            request.Headers.Add("Origin", "http://www.cailele.com/lottery/jx11x5/");
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.8 (KHTML, like Gecko) Chrome/7.0.524.0 Safari/534.8";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = new CookieContainer();

            WebResponse response = request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();
            response.Close();

            var tmp = content.Substring(2, content.Length - 4).Split(new string[] { "\",\"" }, StringSplitOptions.RemoveEmptyEntries);
            if (tmp.Length != 4)
                throw new Exception("请求的结果格式不一致，无法解析！");

            string qihao = tmp.FirstOrDefault(p => p.StartsWith("openTerm")).Split(new string[] { "\":\"" }, StringSplitOptions.RemoveEmptyEntries)[1];
            string opencode = tmp.FirstOrDefault(p => p.StartsWith("openResult")).Split(new string[] { "\":\"" }, StringSplitOptions.RemoveEmptyEntries)[1];

            if (string.IsNullOrEmpty(qihao) || string.IsNullOrEmpty(opencode))
                return null;
            long intqihao = long.Parse(qihao.Replace("-", ""));
            long intissue = long.Parse(issue.Replace("-", ""));

            if (intqihao < intissue)
                return null;
            rs = new Issue() { Number = qihao, WinNumber = opencode, LotteryID = (int)LotteryType.TC11X5, IsNull = intqihao > intissue };



            return rs;
        }
    }

    public class HaoCai1 : Lottery
    {

        public override Issue GetCurrentWin(string issue, DateTime opentime)
        {
            DataSet objDataSet = new DataSet();

            objDataSet.ReadXml("http://www.cailele.com/static/hc1/newlyopenlist.xml");
            //取得期号
            string qihao = objDataSet.Tables[0].Rows[0]["expect"] as string;
            //取得开奖号码
            string opencode = objDataSet.Tables[0].Rows[0]["opencode"] as string;

            string strtime = objDataSet.Tables[0].Rows[0]["opentime"] as string;

            objDataSet.Dispose();
            DateTime getopen;

            if (string.IsNullOrEmpty(strtime) || !DateTime.TryParse(strtime.Trim(), out getopen) || string.IsNullOrEmpty(opencode))
                throw new System.NullReferenceException(LotteryType.HaoCai1.GetName() + "开奖：文件解析出错！");

            Issue open = new Issue() { Number = issue, WinNumber = opencode, LotteryID = (int)LotteryType.HaoCai1 };

            if (getopen.Date > opentime.Date)
                open.IsNull = true;

            else if (getopen.Date < opentime.Date)
                return null;

            return open;
        }
    }
    /// <summary>
    /// 广东快乐十分
    /// </summary>
    public class GDKLSF : Lottery
    {

        public override Issue GetCurrentWin(string issue, DateTime opentime)
        {

            string url = "http://baidu.lehecai.com/lottery/draw/view/544?agentId=5555";
            string opencode = "";
            string qihao = "";


            var client = new WebClient();

            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");


            var data = client.OpenRead(url);

            var reader = new StreamReader(data, Encoding.Default);

            string html = reader.ReadToEnd();
            opencode = html.Substring(html.IndexOf("latest_draw_result =") + 30, 37);
            opencode = opencode.Replace("\"", "");
            qihao = html.Substring(html.IndexOf("latest_draw_phase =") + 21, 10);
            var intqihao = long.Parse(qihao);
            var intissue = long.Parse(issue.Replace("-", ""));
            var rs = new Issue() { Number = qihao, WinNumber = opencode, LotteryID = (int)LotteryType.GDKLSF, IsNull = intqihao > intissue };
            if (intqihao < intissue)
                return null;

            return rs;
        }
    }

    #endregion
}